package com.fxz.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fxz.common.lang.Const;
import com.fxz.common.lang.Result;
import com.fxz.entity.SysRole;
import com.fxz.entity.SysRoleMenu;
import com.fxz.entity.SysUserRole;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fxz
 * @since 2021-05-04
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    /**
     * 通过角色i查询角色信息
     *
     * @param id 角色Id
     * @return 角色信息
     */
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info")
    public Result info(Long id) {
        //获取角色相关联的菜单id
        SysRole role = sysRoleService.getById(id);
        List<SysRoleMenu> roleMenus = sysRoleMenuService.list(
                new LambdaQueryWrapper<SysRoleMenu>()
                        .eq(SysRoleMenu::getRoleId, id)
        );
        List<Long> menuIds = roleMenus.stream().map(menu -> menu.getMenuId()).collect(Collectors.toList());
        role.setMenuIds(menuIds);
        return Result.succ(role);
    }

    /**
     * 模糊查询角色列表
     *
     * @param name 角色名
     * @return 角色列表
     */
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/list")
    public Result list(String name) {
        Page<SysRole> pageData = sysRoleService.page(getPage(), new LambdaQueryWrapper<SysRole>().like(!StringUtils.isBlank(name), SysRole::getName, name));
        return Result.succ(pageData);
    }

    /**
     * 添加角色
     *
     * @param role 角色信息
     */
    @PreAuthorize("hasAuthority('sys:role:save')")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysRole role) {
        role.setCreated(LocalDateTime.now());
        role.setUpdated(LocalDateTime.now());
        role.setStatu(Const.STATUS_ON);
        return Result.succ(sysRoleService.save(role));
    }

    /**
     * 更新角色
     *
     * @param role 角色信息
     */
    @PreAuthorize("hasAuthority('sys:role:update')")
    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysRole role) {
        //更新缓存
        sysUserService.clearUserAuthorityInfoByRoleId(role.getId());

        role.setUpdated(LocalDateTime.now());
        return Result.succ(sysRoleService.updateById(role));
    }

    /**
     * 根据角色id批量删除角色信息
     * @param ids 角色id集合
     */
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @Transactional
    @PostMapping("/delete")
    public Result delete(@RequestBody Long[] ids) {

        //删除所有相关的中间表
        sysRoleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().in(SysRoleMenu::getRoleId, ids));
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getRoleId, ids));

        //同步删除缓存
        Arrays.stream(ids).forEach(id -> {
            //更新缓存
            sysUserService.clearUserAuthorityInfoByRoleId(id);
        });

        //删除角色信息
        return Result.succ(sysRoleService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 为角色分配菜单权限
     *
     * @param id      角色id
     * @param menuIds 菜单id
     */
    @PreAuthorize("hasAuthority('sys:role:perm')")
    @Transactional
    @PostMapping("/perm/{id}")
    public Result perm(@PathVariable("id") Long id, @RequestBody Long[] menuIds) {

        List<SysRoleMenu> roleMenus = new LinkedList<>();

        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(id);
            roleMenus.add(roleMenu);
        });
        //先删除原来的记录 再保存
        sysRoleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
        sysRoleMenuService.saveBatch(roleMenus);

        //删除角色相关的缓存
        sysUserService.clearUserAuthorityInfoByRoleId(id);
        return Result.succ(menuIds);
    }
}
